﻿using Logic;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace Level.Enemies
{
    public class BombDamage : MonoBehaviour
    {
        public float Radius { get; set; }
        public int Damage { get; set; }
        private static int _layerMask;
        private readonly Collider[] _targets = new Collider[15];
        [SerializeField] private BombHealth _health;
        private bool _destroyed;

        private void Start()
    {
        _health.Destroyed += OnKill;
        _layerMask = 1 << LayerMask.NameToLayer(Constants.HittableMask);
    }

    private void OnTriggerEnter(Collider other)
        {
            if (!_destroyed && other.CompareTag(Constants.PlayerTag))
                _health.TakeDamage(Damage);
        }

        private void OnDestroy() =>
            _health.Destroyed -= OnKill;

        private void OnKill()
        {
            _destroyed = true;
            ApplyDamage();
        }

        private void ApplyDamage()
        {
            System.Array.Clear(_targets, 0, _targets.Length);
            var count = Physics.OverlapSphereNonAlloc(transform.position, Radius, _targets, _layerMask);
            var uniqueColliders = new HashSet<Collider>();
            for (var i = 0; i < count; i++) 
                uniqueColliders.Add(_targets[i]);

            foreach (var target in uniqueColliders.Where(target => target))
            {
                if (target.TryGetComponent<IHealth>(out var health))
                    health.TakeDamage(Damage);
            }
            _health.TakeDamage(_health.Max);
        }
    }
}